document.addEventListener('DOMContentLoaded', () => {
    const loginPage = document.getElementById('loginPage');
    const adminDashboard = document.getElementById('adminDashboard');
    const loginBtn = document.getElementById('loginBtn');
    const logoutBtn = document.getElementById('logoutBtn');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const loginMessage = document.getElementById('loginMessage');

    const addSoftwareBtn = document.getElementById('addSoftwareBtn');
    const softwareList = document.getElementById('softwareList');
    const noSoftwareMessage = document.getElementById('noSoftwareMessage');

    const softwareModal = document.getElementById('softwareModal');
    const modalTitle = document.getElementById('modalTitle');
    const softwareForm = document.getElementById('softwareForm');
    const softwareIdInput = document.getElementById('softwareId');
    const softwareNameInput = document.getElementById('softwareName');
    const softwareDescriptionInput = document.getElementById('softwareDescription');
    const softwareLinkInput = document.getElementById('softwareLink');
    const softwareCategoryInput = document.getElementById('softwareCategory');
    const softwareIconClassInput = document.getElementById('softwareIconClass');
    const cancelSoftwareBtn = document.getElementById('cancelSoftwareBtn');

    // Default admin credentials (for this simulation)
    const ADMIN_USERNAME = 'admin';
    const ADMIN_PASSWORD = 'password';

    // --- Login/Logout Logic ---
    function checkLoginStatus() {
        const loggedIn = localStorage.getItem('loggedIn') === 'true';
        if (loggedIn) {
            loginPage.classList.add('hidden');
            adminDashboard.classList.remove('hidden');
            loadSoftwares(); // Load data after successful login
        } else {
            loginPage.classList.remove('hidden');
            adminDashboard.classList.add('hidden');
        }
    }

    loginBtn.addEventListener('click', () => {
        const username = usernameInput.value;
        const password = passwordInput.value;

        if (username === ADMIN_USERNAME && password === ADMIN_PASSWORD) {
            localStorage.setItem('loggedIn', 'true');
            loginMessage.classList.add('hidden');
            checkLoginStatus();
        } else {
            loginMessage.textContent = '用户名或密码错误！';
            loginMessage.classList.remove('hidden');
        }
    });

    logoutBtn.addEventListener('click', () => {
        localStorage.removeItem('loggedIn');
        checkLoginStatus();
        // Clear inputs for next login attempt
        usernameInput.value = ADMIN_USERNAME;
        passwordInput.value = ADMIN_PASSWORD;
        loginMessage.classList.add('hidden');
    });

    // --- Software Management Logic ---
    let softwares = []; // Array to hold software data

    function loadSoftwares() {
        const storedSoftwares = localStorage.getItem('softwares');
        if (storedSoftwares) {
            softwares = JSON.parse(storedSoftwares);
        } else {
            // Initial dummy data if nothing is stored
            softwares = [
                { id: 1, name: "Clash.NET 1.2.7 x64", description: "高效的网络代理工具，支持多平台。", link: "http://qiniu.dywlkj.com/Clash.NET.1.2.7.x64.zip", category: "软件", iconClass: "fas fa-desktop" },
                { id: 2, name: "WordPress 3.6.1", description: "经典版本的WordPress安装包。", link: "http://qiniu.dywlkj.com/wp/wordpress-3.6.1.zip", category: "网站源码", iconClass: "fab fa-wordpress" },
                { id: 3, name: "boomssw.yaml", description: "Clash 配置订阅文件。", link: "http://qiniu.dywlkj.com/boomssw.yaml", category: "Clash Config 订阅地址", iconClass: "fas fa-link" },
                { id: 4, name: "Clash and Dashboard Latest", description: "最新版本的Clash及Dashboard镜像。", link: "http://qiniu.dywlkj.com/clash-and-dashboard-latest.tar", category: "Docker Images", iconClass: "fab fa-docker" },
                { id: 5, name: "Apache Zookeeper 3.8.3", description: "Apache Zookeeper 的二进制安装包。", link: "http://qiniu.dywlkj.com/apache-zookeeper-3.8.3-bin.tar.gz", category: "Linux Shell Tools", iconClass: "fab fa-linux" },
                { id: 6, name: "install-omz.sh", description: "安装 Oh My Zsh 的脚本。", link: "http://qiniu.dywlkj.com/install-omz.sh", category: "Linux Shell Script", iconClass: "fas fa-scroll" }
            ];
            saveSoftwares();
        }
        renderSoftwares();
    }

    function saveSoftwares() {
        localStorage.setItem('softwares', JSON.stringify(softwares));
    }

    function renderSoftwares() {
        softwareList.innerHTML = ''; // Clear existing list
        if (softwares.length === 0) {
            noSoftwareMessage.classList.remove('hidden');
            return;
        }
        noSoftwareMessage.classList.add('hidden');

        softwares.forEach(software => {
            const row = document.createElement('tr');
            row.className = 'border-b border-gray-200 hover:bg-gray-100';
            row.innerHTML = `
                <td class="py-3 px-6 text-left whitespace-nowrap">${software.id}</td>
                <td class="py-3 px-6 text-left font-medium text-gray-900 flex items-center">
                    <i class="${software.iconClass} text-blue-500 mr-3 text-lg"></i>
                    <span>${software.name}</span>
                </td>
                <td class="py-3 px-6 text-left max-w-xs overflow-hidden text-ellipsis whitespace-nowrap">${software.description}</td>
                <td class="py-3 px-6 text-left max-w-xs overflow-hidden text-ellipsis whitespace-nowrap">
                    <a href="${software.link}" target="_blank" class="text-blue-500 hover:underline">${software.link.substring(0, 30)}...</a>
                </td>
                <td class="py-3 px-6 text-left">${software.category}</td>
                <td class="py-3 px-6 text-center">
                    <div class="flex item-center justify-center space-x-2">
                        <button data-id="${software.id}" class="edit-btn w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center hover:bg-blue-600 transition-colors duration-200" title="编辑">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button data-id="${software.id}" class="delete-btn w-8 h-8 rounded-full bg-red-500 text-white flex items-center justify-center hover:bg-red-600 transition-colors duration-200" title="删除">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </div>
                </td>
            `;
            softwareList.appendChild(row);
        });

        // Add event listeners to newly created buttons
        document.querySelectorAll('.edit-btn').forEach(button => {
            button.addEventListener('click', openEditModal);
        });
        document.querySelectorAll('.delete-btn').forEach(button => {
            button.addEventListener('click', deleteSoftware);
        });
    }

    function openModal() {
        softwareModal.classList.remove('hidden');
    }

    function closeModal() {
        softwareModal.classList.add('hidden');
        softwareForm.reset(); // Clear form fields
        softwareIdInput.value = ''; // Clear ID for add mode
    }

    addSoftwareBtn.addEventListener('click', () => {
        modalTitle.textContent = '添加新软件';
        openModal();
    });

    cancelSoftwareBtn.addEventListener('click', closeModal);

    softwareForm.addEventListener('submit', (e) => {
        e.preventDefault();

        const id = softwareIdInput.value;
        const name = softwareNameInput.value;
        const description = softwareDescriptionInput.value;
        const link = softwareLinkInput.value;
        const category = softwareCategoryInput.value;
        const iconClass = softwareIconClassInput.value;

        if (id) {
            // Edit existing software
            const index = softwares.findIndex(s => s.id == id);
            if (index !== -1) {
                softwares[index] = { id: parseInt(id), name, description, link, category, iconClass };
            }
        } else {
            // Add new software
            const newId = softwares.length > 0 ? Math.max(...softwares.map(s => s.id)) + 1 : 1;
            softwares.push({ id: newId, name, description, link, category, iconClass });
        }

        saveSoftwares();
        renderSoftwares();
        closeModal();
    });

    function openEditModal(event) {
        const idToEdit = event.currentTarget.dataset.id;
        const softwareToEdit = softwares.find(s => s.id == idToEdit);

        if (softwareToEdit) {
            modalTitle.textContent = '编辑软件';
            softwareIdInput.value = softwareToEdit.id;
            softwareNameInput.value = softwareToEdit.name;
            softwareDescriptionInput.value = softwareToEdit.description;
            softwareLinkInput.value = softwareToEdit.link;
            softwareCategoryInput.value = softwareToEdit.category;
            softwareIconClassInput.value = softwareToEdit.iconClass;
            openModal();
        }
    }

    function deleteSoftware(event) {
        const idToDelete = event.currentTarget.dataset.id;
        if (confirm('确定要删除此软件吗？')) {
            softwares = softwares.filter(s => s.id != idToDelete);
            saveSoftwares();
            renderSoftwares();
        }
    }

    // Initial check on page load
    checkLoginStatus();
});
